//
//  TSImageFilterViewController.m
//  TSImageFilterDemo
//
//  Created by lichq on 13-12-23.
//  Copyright (c) 2013年 lichq. All rights reserved.
//

#import "TSImageFilterViewController.h"
#import <CQDemoKit/CJUIKitAlertUtil.h>
#import "ImageUtil.h"
#import <QuartzCore/QuartzCore.h>

#import "QTemplet.h"
#import "QImage.h"
#import "QTempletVC.h"

QTempletInfo templetInfo;

#define BOXWidth 45
#define BOXHeight 30

@interface TSImageFilterViewController () <UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    UIImageView *rootImageView;
    UISegmentedControl *seg;
    UIImage *currentImage;
    UIImagePickerController *imagePicker;
    UIScrollView *scrollerView;
    
    UIImage *rootImage;
    UIImageView *boxImageView;
    
    UIButton *exampleBtn;
}

@end

@implementation TSImageFilterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"图片处理";
    
    UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithTitle:@"选择图片" style:UIBarButtonItemStyleBordered target:self action:@selector(changeImageAction)];
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStyleBordered target:self action:@selector(saveImage)];
    self.navigationItem.leftBarButtonItem = left;
    self.navigationItem.rightBarButtonItem = right;
    
    [self setupViews];
    
    UIImage *image = [UIImage imageNamed:@"image1.jpg"];
    currentImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(260, 340)];
    //调用imageWithImageSimple:scaledToSize:方法
    rootImageView.image = currentImage;
    
    boxImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 45, 50)];
    rootImage = [UIImage imageNamed:@"110.png"];
    boxImageView.image = rootImage;
    [scrollerView addSubview:boxImageView];
    
    seg.userInteractionEnabled = YES;
    [self.view addSubview:rootImageView];
}

- (void)setupViews {
    self.view.backgroundColor = [UIColor whiteColor];
    
    rootImageView = [[UIImageView alloc]initWithFrame:CGRectMake(40, 10, 240, 320)];
    
    NSArray *arr = [NSArray arrayWithObjects:@"原图",
                    @"正片叠底",
                    @"添字", @"组合", @"建模", @"模板",
                    @"LOMO1", @"LOMO2", @"LOMO3",
                    @"素描", @"碎片", @"底片",
                    @"黑白", @"复古", @"哥特", @"锐色",@"淡雅", @"酒红", @"青柠", @"浪漫", @"光晕", @"蓝调", @"梦幻", @"夜色", nil];
    
    scrollerView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 340, 320, 100)];
    scrollerView.backgroundColor = [UIColor clearColor];
    scrollerView.indicatorStyle = UIScrollViewIndicatorStyleBlack;//滚动条样式
    scrollerView.showsHorizontalScrollIndicator = YES;
    //显示横向滚动条
    scrollerView.showsVerticalScrollIndicator = NO;//关闭纵向滚动条
    scrollerView.bounces = NO;//取消反弹效果
    scrollerView.pagingEnabled = NO;//划一屏
    scrollerView.contentSize = CGSizeMake(BOXWidth * arr.count, 30);
    [self.view addSubview:scrollerView];
    
    
    seg = [[UISegmentedControl alloc]initWithItems:arr];
    seg.segmentedControlStyle = UISegmentedControlStyleBar;//样式
    //    seg.momentary = YES;//点击后恢复原样
    seg.frame = CGRectMake(0, 50, BOXWidth * arr.count, BOXHeight);
    seg.tintColor = [UIColor blackColor];
    seg.userInteractionEnabled = NO;//关闭用户交互
    [seg addTarget:self action:@selector(changeImage:) forControlEvents:UIControlEventValueChanged];
    [scrollerView addSubview:seg];
    
    
    for(int i = 0; i < [arr count]; i++) {
        UIImageView *bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10+BOXWidth*i, 10, 25, BOXHeight)];
        
        NSString *imageName;
        if (i == 0) {
            imageName = [NSString stringWithFormat:@"%d.png",0];
        } else if (i == CMLomo1) {
            imageName = [NSString stringWithFormat:@"%d.png",CMLomo1];
        } else if (i >= CMHeiBai){
            imageName = [NSString stringWithFormat:@"%d.png",i - CMHeiBai + 2];
        } else {
            imageName = @"image1.jpg";
        }
        
        bgImageView.image = [UIImage imageNamed:imageName];
        [scrollerView addSubview:bgImageView];
    }
}

- (void)changeImageAction {
    [CJUIKitAlertUtil showActionSheetInViewController:self withTitle:@"选择图片" message:nil itemTitles:@[@"相册", @"照相机"] cancleBlock:nil itemClickBlock:^(NSInteger index) {
        if (index == 0) {
            [self chooseImageFromPhoto];
        } else if (index == 1) {
            [self takeImage];
        }
    }];
    
}

- (void)chooseImageFromPhoto {
    //        NSString *string = [[NSBundle mainBundle] pathForResource:@"1110" ofType:@"JPEG"];
    //        currentImage = [UIImage imageWithContentsOfFile:string];
    //        rootImageView.image = currentImage;
    //        seg.userInteractionEnabled = YES;
    //        [self.view addSubview:rootImageView];
    
    imagePicker = [[UIImagePickerController alloc] init];//图像选取器
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//打开相册
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical; //过渡类型,有四种
    //imagePicker.allowsEditing = NO;//禁止对图片进行编辑
    
    [self presentViewController:imagePicker animated:YES completion:NULL];//打开模态视图控制器选择图像
}

- (void)takeImage {
    if( [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] ) {
        imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;//照片来源为相机
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        
        [self presentViewController:imagePicker animated:YES completion:NULL];
    } else {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"该设备没有照相机" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];//获取图片
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);//将拍到的图片保存到相册
    }
    
    currentImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(260, 340)];
    //    currentImage = image;
    
    //调用imageWithImageSimple:scaledToSize:方法
    
    //    [currentImage retain]; //be care
    
    rootImageView.image = currentImage;
    
    boxImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 45, 50)];
    rootImage = [UIImage imageNamed:@"110.png"];
    boxImageView.image = rootImage;
    [scrollerView addSubview:boxImageView];
    
    seg.userInteractionEnabled = YES;
    [self.view addSubview:rootImageView];
    [self dismissViewControllerAnimated:YES completion:NULL];//关闭模态视图控制器
}

- (UIImage *)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);//根据当前大小创建一个基于位图图形的环境
    
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; //根据新的尺寸画出传过来的图片
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();//从当前环境当中得到重绘的图片
    
    UIGraphicsEndImageContext();//关闭当前环境
    
    return newImage;
}

- (void)saveImage {
    [CJUIKitAlertUtil showCancleOKAlertInViewController:self withTitle:@"是否保存" message:nil cancleBlock:nil okBlock:^{
        UIImage *img = rootImageView.image;// 要保存的图片
        UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil); // 保存图片到相册中
    }];
}


- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error != NULL) {
        [CJUIKitAlertUtil showIKnowAlertInViewController:self withTitle:@"保存失败,请重新保存" iKnowBlock:nil];
    } else {
        [CJUIKitAlertUtil showIKnowAlertInViewController:self withTitle:@"保存成功" iKnowBlock:nil];
    }
}

//-(void)move
//{
//    CGPoint fromPoint = imageView.bounds.origin;
//
//    UIBezierPath *movePath = [UIBezierPath bezierPath];
//    [movePath moveToPoint:fromPoint];
//    CGPoint toPoint = CGPointMake(46, 30);
//    [movePath addQuadCurveToPoint:toPoint controlPoint:CGPointMake(toPoint.x, fromPoint.x)];
//
//    //关键帧
//    CAKeyframeAnimation *moveAnim = [CAKeyframeAnimation animationWithKeyPath:@"position"];
//    moveAnim.path = movePath.CGPath;
//    moveAnim.removedOnCompletion = YES;

//    //旋转变化
//    CABasicAnimation *scaleAnim = [CABasicAnimation animationWithKeyPath:@"transform"];
//    scaleAnim.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
//    //x，y轴缩小到0.1,Z 轴不变
//    scaleAnim.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)];
//    scaleAnim.removedOnCompletion = YES;
//
//    //关键帧，旋转组合起来执行
//    CAAnimationGroup *animGroup = [CAAnimationGroup animation];
//    animGroup.animations = [NSArray arrayWithObjects:moveAnim, scaleAnim, nil];
//    animGroup.duration = 1;
//    [imageView.layer addAnimation:moveAnim forKey:nil];
//}

- (void)addText{
    NSLog(@"Dosomething");
    dosomething();
    return;
    
    UIImage *image = [UIImage imageNamed:@"image1.jpg"];
    CGSize size = self.view.frame.size;
    UIGraphicsBeginImageContext(size);
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    NSString *title = @"helo world";
    CGContextTranslateCTM(contextRef, 0, self.view.bounds.size.height);
    CGContextScaleCTM(contextRef, 1.0, -1.0);
    CGContextDrawImage(contextRef, self.view.frame, [image CGImage]);
    
    [[UIColor redColor] set];
    CGContextTranslateCTM(contextRef, 0, self.view.bounds.size.height);
    CGContextScaleCTM(contextRef, 1.0, -1.0);
    UIFont *font = [UIFont boldSystemFontOfSize:40];
    [title drawInRect:CGRectMake(100, 200, 200, 80) withFont:font];
    
    UIImage *res = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    NSArray *savePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *p = [savePath objectAtIndex:0];
    NSLog(@"p = %@",p);
    NSString *dataFilePaht = [p stringByAppendingPathComponent:@"1.png"];
    
    NSData *imageData = UIImagePNGRepresentation(res);
    [imageData writeToFile:dataFilePaht atomically:YES];
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 480-100)];
    [imageView setImage:res];
    [self.view addSubview:imageView];
}

- (void)goTempletVC{
    QTempletVC *templetVC = [[QTempletVC alloc]init];
    UINavigationController *templetNav = [[UINavigationController alloc]initWithRootViewController:templetVC];
    [self presentViewController:templetNav animated:YES completion:NULL];
    //    [self.navigationController pushViewController:templetVC animated:NO];
}

-(void)changeImage:(UISegmentedControl *)segment
{
    UIImage *image1 = [UIImage imageNamed:@"image1.jpg"];
    UIImage *image2 = [UIImage imageNamed:@"image2.jpg"];
    UIImage *imageMuban = [UIImage imageNamed:@"muban1.jpg"];
    QTempletInfo templetInfo = createTempletInfo1();
    imageMuban = [ImageUtil createMubanImage:templetInfo];
    
    if (exampleBtn && segment.selectedSegmentIndex != CMTemplet) {
        [exampleBtn removeFromSuperview];
    }
    
    switch (segment.selectedSegmentIndex) {
        case CMOrigin:{
            rootImageView.image = currentImage;
            break;
        }
#pragma mark - ImageTuceng
        case CMZhengpiandiedi:{
            rootImageView.image = [ImageUtil LayerMultiplyImage:image1 templet:imageMuban];
            break;
        }
            
#pragma mark - ImageCompose
        case CMAddText:{
            [self addText];
            rootImageView.image = [ImageUtil addText:@"hello" ToImage:currentImage];
            break;
        }
        case CMCompose:{
            rootImageView.image = [ImageUtil imageToComposeWithImage1:image1 Image2:image2];
            break;
        }
        case CMTemplet:{
            rootImageView.image = [ImageUtil createMubanImage:templetInfo];
            
            [self goTempletVC];
            /*
             exampleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
             [exampleBtn setFrame:CGRectMake(100, 170, 120, 30)];
             [exampleBtn setTitle:@"模板实例" forState:UIControlStateNormal];
             [exampleBtn setBackgroundColor:[UIColor blackColor]];
             [exampleBtn addTarget:self action:@selector(goTempletVC) forControlEvents:UIControlEventTouchUpInside];
             [self.view addSubview:exampleBtn];
             */
            break;
        }
        case CMComposeMuban:{
            //            rootImageView.image = [ImageUtil imageToComposeWithImage1:image1 Image2:image2 ByImage:imageMuban];
            rootImageView.image = image1;
            break;
        }
            
            
#pragma mark - ImageFilter
        case CMLomo1:{
            rootImageView.image = [ImageUtil imageLomoMethod1:currentImage];
            break;
        }
        case CMLomoNTSC:{
            rootImageView.image = [ImageUtil imageLomoNTSC:currentImage];
            break;
        }
        case CMLomo3:{
            rootImageView.image = [ImageUtil imageLomoMethod3:currentImage];
            break;
        }
        case CMSketch:{
            rootImageView.image = [ImageUtil imageSketch:currentImage];
            break;
        }
        case CMScrap:{
            rootImageView.image = [ImageUtil imageScrap:currentImage];
            break;
        }
        case CMDipian:{
            rootImageView.image = [ImageUtil imageDipian:currentImage];
            break;
        }
            
            
        case CMHeiBai:{
            rootImageView.image = [ImageUtil imageHeibai:currentImage];
            break;
        }
        case CMHuaijiu:{
            rootImageView.image = [ImageUtil imageHuaijiu:currentImage];
            break;
        }
        case CMGete:{
            rootImageView.image = [ImageUtil imageGete:currentImage];
            break;
        }
        case CMRuise:{
            rootImageView.image = [ImageUtil imageRuise:currentImage];
            break;
        }
        case CMDanya:{
            rootImageView.image = [ImageUtil imageDanya:currentImage];
            break;
        }
        case CMJiuhong:{
            rootImageView.image = [ImageUtil imageJiuhong:currentImage];
            break;
        }
        case CMQingning:{
            rootImageView.image = [ImageUtil imageQingning:currentImage];
            break;
        }
        case CMlangman:{
            rootImageView.image = [ImageUtil imageLangman:currentImage];
            break;
        }
        case CMguangyun:{
            rootImageView.image = [ImageUtil imageGuangyun:currentImage];
            break;
        }
        case CMlandiao:{
            rootImageView.image = [ImageUtil imageLandiao:currentImage];
            break;
        }
        case CMmenghuan:{
            rootImageView.image = [ImageUtil imageMenghuan:currentImage];
            break;
        }
        case CMyese:{
            rootImageView.image = [ImageUtil imageYese:currentImage];
            break;
        }
        default:
            break;
    }
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDelay:0.3];
    boxImageView.frame = CGRectMake(BOXWidth*segment.selectedSegmentIndex, 0, BOXWidth, 50);
    [UIView commitAnimations];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
